<template>
  <div>
    <van-dropdown-menu ref="menuRef">
      <van-dropdown-item v-model="state.selectCqdd" :title="cqddTitle" :options="option1" @change="onChangeCqdd" />
      <van-dropdown-item :disabled="!state.selectCqdd" :title="jqzTitle" v-model="state.selectJqz" :options="option2"
        @change="onChangeJqz" />
      <van-dropdown-item :disabled="!state.selectJqz" :title="jingTitle" v-model="state.selectJing" :options="option3"
        @change="onChangeJing" />
    </van-dropdown-menu>

    <van-overlay :show="showEdit" @click="showEdit = false">
      <div class="edit-box">
        <el-card class="card" @click.stop>
          <template #header>
            <div class="card-header">
              <h4 v-if="state.type == 1">新增采气大队</h4>
              <h4 v-if="state.type == 2">新增集气站</h4>
              <h4 v-if="state.type == 3">新增井场</h4>
              <h4 v-if="state.type == 4">新增井</h4>
            </div>
          </template>
          <el-form ref="formRef" :model="formData" :rules="rules" size="large" label-position="top">
            <el-form-item label="名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入名称"></el-input>
            </el-form-item>
          </el-form>
          <van-button type="primary" block @click="onSumbit">保 存</van-button>
        </el-card>
      </div>
    </van-overlay>
    <div class="button-group">
      <van-button class="btn-item" type="primary" block @click="onAdd(1)">新增采气大队</van-button>
      <van-button class="btn-item" type="primary" block @click="onAdd(2)">新增集气站</van-button>
      <van-button class="btn-item" type="primary" block @click="onAdd(3)">新增井场</van-button>
      <van-button class="btn-item" type="primary" block @click="onAdd(4)">新增井</van-button>
      <van-button class="btn-item" type="danger" block @click="onRemove(1)">删除采气大队</van-button>
      <van-button class="btn-item" type="danger" block @click="onRemove(2)">删除集气站</van-button>
      <van-button class="btn-item" type="danger" block @click="onRemove(3)">删除井场</van-button>
      <van-button class="btn-item" type="danger" block @click="onRemove(4)">删除井</van-button>
    </div>

    <van-popup v-model:show="showJing" round position="bottom" :style="{ height: '70%' }" closeable>
      <h4 class="title">{{ cqddTitle }} - {{ jqzTitle }} - {{ jingTitle }}</h4>
      <div class="list">
        <el-card class="item" v-for="item in list" :key="item.id">
          <div class="content">
            {{ item.jingdetail }}
            <van-icon name="delete-o" color="blue" size="20" @click="onRemoveJing(item)" />
          </div>
        </el-card>
      </div>
    </van-popup>
  </div>

</template>

<script setup>
import { onMounted, ref, reactive, computed } from "vue";
import { ElMessage } from "element-plus";
import Api from "@/api";
const showEdit = ref(false);
const option1 = ref([]);
const option2 = ref([]);
const option3 = ref([]);
const showJing = ref(false)
const list = ref([]);
const state = reactive({
  selectCqdd: "",
  selectJqz: "",
  selectJing: '',
  type: 1,
});

const formData = ref({
  name: "",
});

const rules = {
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
};

const cqddTitle = computed(() => {
  return (
    option1.value.find((item) => item.value === state.selectCqdd)?.text ||
    "请选择采气大队"
  );
});

const jqzTitle = computed(() => {
  return (
    option2.value.find((item) => item.value === state.selectJqz)?.text ||
    "请选择集气站"
  );

});

const jingTitle = computed(() => {
  return (
    option3.value.find((item) => item.value === state.selectJing)?.text ||
    "请选择井场"
  );
});

const formRef = ref(null);
const onChangeCqdd = (value) => {
  state.selectJqz = "";
  state.selectJing = "";
  option2.value = [];
  option3.value = [];
  getJqzSelect(value);
};
const onAdd = (type) => {
  state.type = type;
  if (type == 2 || type == 3) {
    if (!state.selectCqdd) {
      ElMessage.error("请选择采气大队");
      return;
    }
    if (type == 3 && !state.selectJqz) {
      ElMessage.error("请选择集气站");
      return;
    }
  }
  showEdit.value = true;
};

const getCqddSelect = async () => {
  const { result } = await Api.getCqddSelect();
  option1.value = (result || []).map((item) => ({
    text: item.cqdd,
    value: item.id,
  }));
};

const getJqzSelect = async () => {
  const { result } = await Api.getJqzSelect({ cqddId: state.selectCqdd });
  option2.value = (result || []).map((item) => ({
    text: item.jqz,
    value: item.id,
  }));
};

const getJingSelect = async () => {
  const { result } = await Api.getJingSelect({ cqddId: state.selectCqdd, jqzid: state.selectJqz });
  console.log(result);
  option3.value = (result || []).map((item) => ({
    text: item.jing,
    value: item.id,
  }));
};

const getJingDetailSelect = async () => {
  const { result } = await Api.getJingDetailSelect({
    cqddId: state.selectCqdd,
    jqzid: state.selectJqz,
    jingid: state.selectJing,
  });
  list.value = (result || []);
}


const onSumbit = () => {
  const handlerSuccess = () => {
    showEdit.value = false;
    formData.value.name = "";
    ElMessage.success({
      message: '保存成功',
      duration: 1000,
    });
    refresh();
  };
  const submitData = () => {

    const params = {
      name: formData.value.name,
      cqddId: state.selectCqdd,
      cqddName: cqddTitle.value.includes('请选择') ? '' : cqddTitle.value,
      jqzId: state.selectJqz,
      jqzName: jqzTitle.value.includes('请选择') ? '' : jqzTitle.value,
      jingId: state.selectJing,
      jingName: jingTitle.value.includes('请选择') ? '' : jingTitle.value,
    }
    if (state.type == 1) {
      return Api.saveCqdd(params);
    }
    if (state.type == 2) {
      return Api.saveJqz(params);
    }
    if (state.type == 3) {
      return Api.saveJing(params)
    }
    if (state.type == 4) {
      return Api.saveJingDetail(params)
    }
  }
  formRef.value.validate((valid) => {
    if (valid) {
      submitData().then(handlerSuccess)
    } else {
      console.log("error submit!!");
      return false;
    }
  });
};

const refresh = () => {
  getCqddSelect();
  if (state.selectCqdd) getJqzSelect();
  if (state.selectJqz) getJingSelect();
};

const onRemove = async (type) => {
  state.type = type;
  if (type == 1 && !state.selectCqdd) {
    ElMessage.error("请选择要删除的采气大队");
    return;
  }
  if (type == 2 && !state.selectJqz) {
    ElMessage.error("请选择要删除的集气站");
    return;
  }

  if (type == 3) {
    if (!state.selectCqdd || !state.selectJqz) {
      ElMessage.error("请先选择采集大队和集气站");
      return;
    }
  }

  if (type == 4) {
    if (!state.selectJing) {
      ElMessage.error("请先选择井场");
      return;
    }

    await getJingDetailSelect();
    showJing.value = true;
    return
  }

  const name = type == 1 ? cqddTitle.value : type == 2 ? jqzTitle.value : jingTitle.value;

  const submitData = () => {
    const handlerSuccess = () => {
      ElMessage.success({
        message: '删除成功',
        duration: 1000,
      });
      if (type == 1) {
        state.selectCqdd = ''
        getCqddSelect()
      }
      if (type == 2) {
        state.selectJqz = ''
        getJqzSelect()
      }
      if (type == 3) {
        state.selectJing = ''
        getJingSelect()
      }
    };
    if (type == 1) {
      return Api.removeCqdd({ id: state.selectCqdd }).then(handlerSuccess);
    }
    if (type == 2) {
      return Api.removeJqz({ id: state.selectJqz }).then(handlerSuccess);
    }
    if (type == 3) {
      return Api.removeJing({ id: state.selectJing }).then(handlerSuccess);
    }
  }
  showConfirmDialog({
    title: '提示',
    message:
      `是否确认删除${name}？`,
  })
    .then(() => {
      // on confirm
      submitData();
    })
    .catch(() => {
      // on cancel
    });
}


const onRemoveJing = (item) => {
  showConfirmDialog({
    title: '提示',
    message:
      `是否确认删除${item.jingdetail}？`,
  })
    .then(() => {
      Api.removeJingDetail({
        id: item.id,
      }).then(res => {
        ElMessage.success({
          message: '删除成功',
          duration: 1000,
        });
        getJingDetailSelect();
      });
    })
    .catch(() => {
      // on cancel
    });
}

const onChangeJqz = () => {
  state.selectJing = "";
  option3.value = [];
  getJingSelect()
};

const onChangeJing = () => {
  getJingDetailSelect()
}


onMounted(() => {
  getCqddSelect();
});
</script>

<style scoped lang="scss">
.button-group {
  padding: 10px;

  .btn-item {
    margin-bottom: 10px;
  }
}

.edit-box {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;

  .card {
    width: 85%;
  }
}

.list {
  padding: 10px;

  .item {
    margin-bottom: 10px;
  }

  .content {
    display: flex;
    justify-content: space-between;
  }
}

.title {
  padding: 15px 10px;
  text-align: center;
}
</style>
